// app/controller/Goodss.js
const Controller = require('egg').Controller;

function toInt(str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class GoodsController extends Controller {
  // 获取商品列表
  async index() {
    const ctx = this.ctx;
    const query = {
      limit: toInt(ctx.query.limit),
      offset: toInt(ctx.query.offset),
    };
    ctx.body = await ctx.model.Goods.findAll(query);
  }

  // 根据id获取商品信息
  async show() {
    const ctx = this.ctx;
    ctx.body = await ctx.model.Goods.findByPk(toInt(ctx.params.id));
  }
  // 创建商品
  async create() {
    const ctx = this.ctx;
    const { name, describe, price, id, gain, img } = ctx.request.body;
    const obj = { name, describe, price, id, gain, img };
    const Goods = await ctx.model.Goods.create(obj);
    ctx.status = 201;
    ctx.body = Goods;
  }
  // 更新商品
  async update() {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const Goods = await ctx.model.Goods.findByPk(id);
    if (!Goods) {
      ctx.status = 404;
      return;
    }

    const { name, describe, price, gain, img } = ctx.request.body;
    const obj = { name, describe, price, gain, img };
    await Goods.update(obj);
    ctx.body = Goods;
  }

  // 删除商品根据id
  async destroy() {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const Goods = await ctx.model.Goods.findByPk(id);
    if (!Goods) {
      ctx.status = 404;
      return;
    }

    await Goods.destroy();
    ctx.status = 200;
  }
}

module.exports = GoodsController;
